package com.turtledove.storyalbum.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Environment;
import android.util.Log;
import android.view.Display;

public class UtilsCommon {

	static int time_out = 30;
	static int time_current = 0;
	static Thread t;

	public static Point getSizeScreen(Activity mActivity) {
		Display display = mActivity.getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		return size;
	}

	// resize img
	public static Bitmap reSizeFile(File f) {
		int SIZE_IMAGE_ALLOW = 200;
		try {
			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// The new size we want to scale to
			final int REQUIRED_SIZE = SIZE_IMAGE_ALLOW;

			// Find the correct scale value. It should be the power of 2.
			int scale = 1;
			while (o.outWidth / scale / 2 >= REQUIRED_SIZE
					&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
				scale *= 2;

			// Decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	public static boolean downLoadFile(Context context, String urlDownload,
			String urlFolder) {
		String nameImage = urlDownload.substring(urlDownload.lastIndexOf("/"));
		String urlString = urlDownload;
		urlString = urlString.replaceAll(" ", "%20");
		URL url;
		try {
			url = new URL(urlString);
			URLConnection conexion = url.openConnection();
			conexion.connect();
			int lenghtOfFile = conexion.getContentLength();
			InputStream is = url.openStream();
			File testDirectory = new File(urlFolder);
			if (!testDirectory.exists()) {
				testDirectory.mkdir();
			}
			FileOutputStream fos = new FileOutputStream(testDirectory + "/"
					+ nameImage);
			byte data[] = new byte[1024];
			int count = 0;
			long total = 0;
			int progress = 0;

			time_current = 0;
			t = new Thread(new Runnable() {

				@SuppressWarnings("deprecation")
				@Override
				public void run() {
					// TODO Auto-generated method stub
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					time_current++;
					if (time_current > time_out)
						t.stop();
				}
			});
			t.start();

			while ((count = is.read(data)) != -1) {
				if (time_current > time_out) {
					fos.write(data, 0, count);
					is.close();
					fos.close();
					return false;
				}
				total += count;
				int progress_temp = (int) total * 100 / lenghtOfFile;
				if (progress_temp % 10 == 0 && progress != progress_temp) {
					progress = progress_temp;
				}
				fos.write(data, 0, count);
			}
			is.close();
			fos.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	// void delete item in folder
	public static int deleteFile(File f) {
		try {
			String[] flist = f.list();
			for (int i = 0; i < flist.length; i++) {
				File temp = new File(f.getAbsolutePath() + "/" + flist[i]);
				if (temp.isDirectory()) {
					deleteFile(temp);
					temp.delete();
				}
				temp.delete();
			}
			return 1;
		} catch (Exception e) {
		}
		return 0;
	}

	// void create folder
	public static String createFolder(String nameFolder) {
		try {
			File pictures = new File(Environment.getExternalStorageDirectory()
					+ "/" + "DCIM");
			if (!pictures.exists()) {
				pictures.mkdir();
			}
			File facebookFolder = new File(pictures + "/" + nameFolder);
			if (!facebookFolder.exists()) {
				facebookFolder.mkdir();
			}
			return facebookFolder.toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return nameFolder;
	}

	public static void copyFile(InputStream in, OutputStream out)
			throws IOException {
		try {
			byte[] buffer = new byte[1024];
			int read;
			while ((read = in.read(buffer)) != -1) {
				out.write(buffer, 0, read);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public static String copyFileAssets(Context mContext, String nameImage) {
		String url = "";
		AssetManager assetManager = mContext.getAssets();
		InputStream in = null;
		OutputStream out = null;
		try {
			in = assetManager.open("img/" + nameImage);
			String urlFoler = createFolder("/StoryAlbum/");
			out = new FileOutputStream(urlFoler + File.separator + nameImage);
			url = urlFoler+"/"+nameImage;
			copyFile(in, out);
			in.close();
			in = null;
			out.flush();
			out.close();
			out = null;
		} catch (IOException e) {
			Log.e("Luong", "Luong____________Failed to copy asset file: "
					+ nameImage, e);
		}
		return url;
	}
}
